package com.wehealth;

//import android.app.Fragment;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.acl.Group;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import u.aly.aa;

import com.umeng.analytics.MobclickAgent;
import com.wehealth.adapter.Adapter_NewsList;
import com.wehealth.adapter.Adapter_QuestionList;
import com.wehealth.dm.QuestionData;
import com.wehealth.dm.User;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.JsonReader;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;



public class Question_List extends Fragment{
	
	
	
	private static  String JSONResult;
	private List<QuestionData> listData;
	private static final int NET_ERROR = -100;
	private static final int NOT_RECORD = -101;
	private static final int NOUSER_ERROR =-102;
	private MainActivity context;
	private User user;
	private ListView listView;
	private ProgressBar mProgress;
			
	public  Question_List()
	{
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.question_list, null);
	}
	
	
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);

		MainActivity activity = (MainActivity)getActivity();
		context = activity ;
		mProgress =(ProgressBar)context.findViewById(R.id.question_progress);
		mProgress.setVisibility(View.VISIBLE);
		user = context.getUserInfo();
	   listView = (ListView) context.findViewById(R.id.questionlist);  
		   if(user.getUserId() == -1){
		        openDialog(NOUSER_ERROR);
		}else{
				ConnService();
		}
		
		MobclickAgent.openActivityDurationTrack(false);
		//返回主页按钮-------------------------------------------------------//
		 Button bBack = (Button) activity.findViewById(R.id.bBack_NewsList);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
				    context.switchContentHome();
				}
			});
			
		//------------------------------------------------------------------//
		
		 
		 
	}
	
	
	
	private void  ConnService(){
		
		//读取接口数据
		new Thread(){
			@Override
			public void run(){
			//你要执行的方法
				try {
					InitThisView();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			//执行完毕后给handler发送一个空消息
			handler.sendEmptyMessage(0);
			}
			}.start();
	}
	
	private void  InitThisView() throws IOException
	{
		 String urlAPI = "http://www.552120.com:8092/Question_GetList.aspx";
		 HttpPost httpRequest= new HttpPost(urlAPI);
		 List <NameValuePair> params = new ArrayList <NameValuePair>(); 
	
		 int userId =  user.getUserId();
		 String userID = String.valueOf(userId);
		 
		 String drID ="0";
		 String departID ="0";
		 String cpmpleted= "0";
		 
		 params.add(new BasicNameValuePair("userID",userID));
		 params.add(new BasicNameValuePair("drID",drID));
		 params.add(new BasicNameValuePair("departmentID",departID));
		 params.add(new BasicNameValuePair("isCompleted",cpmpleted));
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);		 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {	
				 JSONResult = EntityUtils.toString(httpResponse.getEntity()); 
			 }		 
		 }
		 catch(Exception e)
		 {		
			 Log.e("error:",  e.toString());
		 }

	}
	
	
	
	//定义Handler对象
	private Handler handler =new Handler(){
		@Override
		public void handleMessage(Message msg){
		super.handleMessage(msg);
		//处理UI
		if(JSONResult ==null){
			openDialog(NET_ERROR);
		}else{
			mProgress.setVisibility(View.VISIBLE);
			BindList(JSONResult);
			JSONResult =null;
		}
		}
	};
	

	
	//将JSON数据绑定到LISTVIEW
	private void BindList(String strJSON)
	{
		    try
		    {
			    JSONObject jsonObject = new JSONObject(strJSON); 
			    JSONArray  aNews =  new JSONArray( jsonObject.getString("result") );  
			    listData = new ArrayList<QuestionData>();
			    if(aNews.length() ==0){
			    	openDialog(NOT_RECORD);
			    	return;
			    }
			    for(int i=0; i<aNews.length(); i++)
			    {
			    	QuestionData  question = new QuestionData();
			    	question.setQID(aNews.getJSONObject(i).getString("QID"));
			    	question.setDrID(aNews.getJSONObject(i).getString("drID"));
			    	question.settime(aNews.getJSONObject(i).getString("time"));
                question.setDepartment(aNews.getJSONObject(i).getString("departmentID"));
                question.setDepartName(aNews.getJSONObject(i).getString("departmentName"));
			    	String cmp =aNews.getJSONObject(i).getString("isCompleted");
			    	int index = Integer.valueOf(cmp);
			    	question.setisCompleted(index);
			    	question.setDesciption(aNews.getJSONObject(i).getString("description"));
			    	listData.add(question);
			    }
		        Log.d("SIMMON","BindList aNews.length()= "+aNews.length());
			    updateListViewData(listData);
		    }
		    catch(JSONException ex)
		    {
		    		Log.e("JSON Error: ", ex.toString()); 
		    }
	}
	
	
	private  void updateListViewData(List<QuestionData> datas ){

 
	    Adapter_QuestionList adapter = new Adapter_QuestionList(context, datas);
	    Log.d("SIMMON","updateListViewData   adapter="+adapter);
	    Log.d("SIMMON","updateListViewData   listView="+listView);
       listView.setAdapter(adapter);
        //SIMMON_ADD begin
        listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int pos, long pos2) {
				// TODO Auto-generated method stub
				Question_reply reply = new Question_reply();
				
				//这一处将来要进行修改
				//news_message.setNewsId(listDataId.get(pos));
				//listData.get(pos).getQID();
				//Log.d("SIMMON","qid ="+listData.get(pos).getQID());
				reply.setData(listData.get(pos));
				
				if (getActivity() instanceof MainActivity)
				{
					MainActivity activity = (MainActivity) getActivity();
					activity.switchContent(reply);
				}
				
			}
		});
		
	}
	
	
    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPageEnd("Question_List"); 
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onPageStart("Question_List"); 
    }

//
//	@Override
//	public boolean onKey(View arg0, int arg1, KeyEvent event) {
//		// TODO Auto-generated method stub
//        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && 
//        		event.getAction() == KeyEvent.ACTION_DOWN) {
//			Home vHome = new Home();
//			if (getActivity() instanceof MainActivity)
//			{
//				MainActivity activity = (MainActivity) getActivity();
//				
//				activity.switchContent(vHome);
//			}
//		}
//		return true;
//	}

    
	  private void openDialog(final int result){
			mProgress.setVisibility(View.GONE);
	        AlertDialog.Builder builder = new AlertDialog.Builder(context); 
	        builder.setIcon(null);
	        String login_result = context.getString(R.string.regist_fail);
	    
	        switch (result) {
	        case NET_ERROR:
	            login_result = getString(R.string.net_connet_fail);
	            break;
	        case NOT_RECORD:
	            login_result = getString(R.string.question_no_record);
	            break;
	        case NOUSER_ERROR:
	            login_result = getString(R.string.cons_submit_nouser);
	            break;
	      }
	         TextView textview = new TextView(context);
	         textview.setText(login_result);
	         textview.setTextColor(Color.BLACK);
	         textview.setTextSize(18);

	         textview.setGravity(Gravity.CENTER);
	         builder.setView(textview);
	         
	         
	         builder.setPositiveButton("确定", new AlertDialog.OnClickListener() {
	             @Override
	             public void onClick(DialogInterface arg0, int arg1) {
	                 // TODO Auto-generated method stub
	                         Home vHome = new Home();
	                         context.switchContent(vHome); 
	             }
	             
	         });
	         builder.create().show();
	         
	     }
    
}



